<template>
  <div class="AdminRoleList">
    <div class="loadBox"></div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }"
        ><i class="lh lh-sys fw_100"></i
      ></el-breadcrumb-item>
      <el-breadcrumb-item>系统设置</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content_Box box-shadow mt_15">
      <div class="mb_10 align-left pl_10">
        <span class="addOK" @click="addRowShowBtn">新增角色</span>
      </div>
      <div class="tableMaxBox">
        <el-table :data="adminRoleList" stripe>
          <el-table-column
            prop="id"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column prop="name" label="角色名称">
            <template slot-scope="{ row }">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="desc" label="人数">
            <template slot-scope="{ row }">
              <span
                class="u text-primary"
                style="cursor: pointer"
                @click="toAdminList(row)"
                >{{ row.sum }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="desc" label="备注"></el-table-column>
          <el-table-column label="操作" text-align="right">
            <template slot-scope="{ row }">
              <el-link type="primary" class="InfoFont" @click="redactBtn(row)"
                >编辑</el-link
              >
              <!-- <el-link type="success" class="InfoFont" @click="lookMember(row)">查看成员</el-link> -->
              <!-- <el-link type="danger" class="InfoFont" @click="deleteRole(row)">删除</el-link> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 添加角色 -->
    <el-dialog
      title="新增角色"
      :visible.sync="addRowShow"
      width="800px"
      :before-close="close"
      :close-on-click-modal="false"
    >
      <div class="auditCentent">
        <div class="row-info clear">
          <div class="fl title-key">
            <i class="lhadmin lhadmin-wujiaoxing"></i><span>角色名称：</span>
          </div>
          <div class="fl list-cont">
            <el-input
              v-model="addRoleArr.name"
              placeholder="请输入角色名称"
            ></el-input>
          </div>
        </div>
        <!-- <div class="row-info clear">
					<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i><span>角色类型：</span></div>
					<div class="fl list-cont">
						<el-select v-model="addRoleArr.type" placeholder="请选择角色类型">
							<el-option v-for="item in roleTypeArr" :key="item.id" :label="item.name" :value="item.id"> </el-option>
						</el-select>
					</div>
				</div> -->
        <div class="row-info clear">
          <div class="fl title-key"><span>备注：</span></div>
          <div class="fl list-cont">
            <el-input
              type="textarea"
              :rows="2"
              v-model="addRoleArr.desc"
              placeholder="请输入内容"
            ></el-input>
          </div>
        </div>
        <div class="clear"></div>
        <div class="clear mt_20">
          <div
            class="mb_10 roleFunctionBox"
            v-for="(item, index) in roleFunctionArr"
            :key="index"
          >
            <div class="roleTitle">
              <h3>
                <span class="mr_10">{{ item.name }}</span>
                <span class="">
                  <el-checkbox
                    v-model="item.checkAllShow"
                    @change="handleCheckAllChange($event, index)"
                    >全选</el-checkbox
                  >
                </span>
              </h3>
            </div>
            <div
              class="pl_10 pb_10"
              v-for="(child, index) in item.child"
              :key="index"
            >
              <div class="menuName fl">{{ child.name }} :</div>
              <div class="menFunction pl_10 pt_10 fl">
                <el-checkbox-group v-model="addRoleArr.checkedCities">
                  <el-checkbox
                    v-for="functionArr in child.child"
                    :label="functionArr.id"
                    :key="functionArr.id"
                    >{{ functionArr.name }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
              <div class="clear"></div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" style="text-align: center">
        <span class="btnOK mr_20" @click="addRoleSubmit">确 定</span>
        <span class="resetBtn" @click="close">取 消</span>
      </div>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="readctRoleShow"
      width="800px"
      :before-close="close"
      :close-on-click-modal="false"
    >
      <div class="auditCentent">
        <div class="row-info clear">
          <div class="fl title-key">
            <i class="lhadmin lhadmin-wujiaoxing"></i><span>角色名称：</span>
          </div>
          <div class="fl list-cont">
            <span>{{ addRoleArr.name }}</span>
          </div>
        </div>
        <!-- <div class="row-info clear">
					<div class="fl title-key"><i class="lhadmin lhadmin-wujiaoxing"></i><span>角色类型：</span></div>
					<div class="fl list-cont">
						<el-select v-model="addRoleArr.type" placeholder="请选择角色类型">
							<el-option v-for="item in roleTypeArr" :key="item.id" :label="item.name" :value="item.id"> </el-option>
						</el-select>
					</div>
				</div> -->
        <div class="row-info clear">
          <div class="fl title-key"><span>备注：</span></div>
          <div class="fl list-cont">
            <el-input
              type="textarea"
              :rows="2"
              v-model="addRoleArr.desc"
              placeholder="请输入内容"
            ></el-input>
          </div>
        </div>
        <div class="clear"></div>
        <div class="clear mt_20">
          <div
            class="mb_10 roleFunctionBox"
            v-for="(item, index) in roleFunctionArr"
            :key="index"
          >
            <div class="roleTitle">
              <h3>
                <span class="mr_10">{{ item.name }}</span>
                <el-checkbox
                  v-model="item.checkAllShow"
                  @change="handleCheckAllChange($event, index)"
                  >全选</el-checkbox
                >
              </h3>
            </div>
            <div
              class="pl_10 pb_10"
              v-for="(child, index) in item.child"
              :key="index"
            >
              <div class="menuName fl">{{ child.name }} :</div>
              <div class="menFunction fl pl_10 pt_10">
                <el-checkbox-group v-model="addRoleArr.checkedCities">
                  <el-checkbox
                    v-for="functionArr in child.child"
                    :label="functionArr.id"
                    :key="functionArr.id"
                    >{{ functionArr.name }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
              <div class="clear"></div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" style="text-align: center">
        <span class="btnOK mr_20" @click="readctSubmit">确 定</span>
        <span class="resetBtn" @click="close">取 消</span>
      </div>
    </el-dialog>
  </div>
</template>
<script>
var common = require('../../static/tool.js')
import { mainfun } from '../assets/js/main.js'
import { publicData } from '../assets/js/data.js'
import { fetchRoleList } from '@/api/user.js'
export default {
  name: 'AdminRoleList',
  data() {
    return {
      windowSizeHeight: document.documentElement.clientHeight, //浏览器可视化窗口的大小
      screenHeight: document.documentElement.clientHeight,
      manageInfo: JSON.parse(sessionStorage.getItem('manageInfo')),
      url: common.url,
      adminRoleList: [], //角色数据
      addRowShow: false, //添加角色弹框
      readctRoleShow: false, //编辑角色
      addRoleArr: {
        //添加角色
        id: '',
        name: '',
        checkedCities: [],
        desc: ''
        // type: ''
      },
      roleFunctionArr: [], //权限列表

      checkAll: false,
      roleTypeArr: [
        { id: '1', name: '管理员' },
        { id: '2', name: '销售' },
        { id: '3', name: '销售总监' },
        { id: '4', name: '渠道' },
        { id: '5', name: '运营' }
      ],

      channel: 1 // 区分商户角色
    }
  },
  watch: {
    $route: {
      handler: function (val, oldVal) {
        this.channel = val.query.channel
        this.startResult()
      },
      deep: true,
      immediate: true,
    }
  },
  mounted() {
    // this.startResult()
  },
  methods: {
    startResult() {
      if (!sessionStorage.getItem('manageInfo')) {
        // 判断是否登录
        window.location = 'login.html'
        return
      }
      this.getListPermissions()
      this.getListRole() //获取角色列表
    },
    // 全选
    handleCheckAllChange(type, index) {
      let roleFunctionArr = [...this.roleFunctionArr[index].child] //角色权限数组
      if (type) {
        for (let i = 0;i < roleFunctionArr.length;i++) {
          for (let k = 0;k < roleFunctionArr[i].child.length;k++) {
            this.addRoleArr.checkedCities.push(roleFunctionArr[i].child[k].id)
          }
        }
        let array = []
        for (let b = 0;b < this.addRoleArr.checkedCities.length;b++) {
          if (array.indexOf(this.addRoleArr.checkedCities[b]) === -1) {
            array.push(this.addRoleArr.checkedCities[b])
          }
        }
        this.addRoleArr.checkedCities = array
      } else {
        let arr = []
        for (let i = 0;i < roleFunctionArr.length;i++) {
          for (let k = 0;k < roleFunctionArr[i].child.length;k++) {
            arr.push(roleFunctionArr[i].child[k].id)
          }
        }
        for (let m = 0;m < arr.length;m++) {
          for (let j = 0;j < this.addRoleArr.checkedCities.length;j++) {
            if (this.addRoleArr.checkedCities[j] == arr[m]) {
              this.addRoleArr.checkedCities.splice(j, 1)
            }
          }
        }
      }
    },
    removeByValue(arr, val) {
      for (var i = 0;i < arr.length;i++) {
        if (arr[i] == val) {
          arr.splice(i, 1)
          break
        }
      }
    },
    async getListRole() {
      try {
        let ret = await fetchRoleList({ channel: this.channel })
        this.adminRoleList = ret.list
      } catch (err) {
        console.log(err)
      }
    },
    getListPermissions() {
      //获取权限列表
      let fn = new FormData()
      fn.append('role_id', '')
      fn.append('channel', this.channel) //区分渠道
      this.$http.post(this.url + '/menu/menulist', fn).then(
        res => {
          if (res.data.msg == '查询成功' || res.data.code == '200') {
            this.roleFunctionArr = res.data.data
            for (let i = 0;i < this.roleFunctionArr.length;i++) {
              let key = 'checkAllShow'
              let value = false
              this.roleFunctionArr[i][key] = value
            }
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },

    close() {
      //清空
      this.addRowShow = false //添加角色弹框
      this.readctRoleShow = false //编辑角色
      this.addRoleArr = { id: '', name: '', checkedCities: [], desc: '' }
    },
    addRowShowBtn() {
      //添加角色
      this.addRowShow = true
      let roleFunctionArr = [...this.roleFunctionArr] //角色权限数组
      for (let i = 0;i < roleFunctionArr.length;i++) {
        //循环数据把全选都变为false
        roleFunctionArr[i].checkAllShow = false
      }
    },
    // 提交添加角色
    addRoleSubmit() {
      if (this.addRoleArr.name == '') {
        this.$message.error('请输入必填项')
        return
      }
      let function_id = [] //最终的提交id
      let grandfather_id = [] //记录订单id
      let father_id = [] //记录父级id
      let checkedCities = [...this.addRoleArr.checkedCities] //当选择的id
      let roleFunctionArr = [...this.roleFunctionArr] //角色权限数组
      for (let i = 0;i < checkedCities.length;i++) {
        for (let n = 0;n < roleFunctionArr.length;n++) {
          for (let k = 0;k < roleFunctionArr[n].child.length;k++) {
            for (let j = 0;j < roleFunctionArr[n].child[k].child.length;j++) {
              if (checkedCities[i] == roleFunctionArr[n].child[k].child[j].id) {
                let grandfatherNum = grandfather_id.indexOf(roleFunctionArr[n].id)
                if (grandfatherNum == -1) {
                  grandfather_id.push(roleFunctionArr[n].id)
                }
                let fatherNum = father_id.indexOf(roleFunctionArr[n].child[k].id)
                if (fatherNum == -1) {
                  father_id.push(roleFunctionArr[n].child[k].id)
                }
              }
            }
          }
        }
      }
      function_id = grandfather_id.concat(father_id, checkedCities)
      let permissions = function_id.join(',')
      if (this.addRoleArr.desc == null) {
        this.addRoleArr.desc = ''
      }
      let fn = new FormData()
      fn.append('name', this.addRoleArr.name) //角色名称
      fn.append('permissions', permissions) //权限id
      fn.append('desc', this.addRoleArr.desc) //备注
      // fn.append('type', this.addRoleArr.type) //角色类型
      fn.append('channel', this.channel) //区分渠道
      this.$http.post(this.url + '/role/addRole', fn).then(
        res => {
          if (res.data.msg == '查询成功' || res.data.code == '200') {
            this.$message.success('添加成功！')
            this.addRowShow = false
            this.close()
            this.getListRole() //获取角色列表
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },
    redactBtn(row) {
      //编辑
      // console.log(row)
      let fn = new FormData()
      fn.append('role_id', row.id)
      fn.append('channel', this.channel) //区分渠道
      this.$http.post(this.url + '/menu/menulist', fn).then(
        res => {
          if (res.data.msg == '查询成功' || res.data.code == '200') {
            let roleFunctionArr = res.data.data
            roleFunctionArr = [...roleFunctionArr] //角色权限数组
            for (let i = 0;i < roleFunctionArr.length;i++) {
              // let type = false;
              for (let k = 0;k < roleFunctionArr[i].child.length;k++) {
                for (let j = 0;j < roleFunctionArr[i].child[k].child.length;j++) {
                  if (roleFunctionArr[i].child[k].child[j].is_check == '1') {
                    //is_check 1为选中  0未选中
                    this.addRoleArr.checkedCities.push(roleFunctionArr[i].child[k].child[j].id)
                  } else {
                    // type = true;
                  }
                }
              }
              // if(!type){
              // this.roleFunctionArr[i].checkAllShow = true;
              // }
            }
            // console.log(this.roleFunctionArr)
            this.addRoleArr.name = row.name
            this.addRoleArr.desc = row.desc
            this.addRoleArr.id = row.id
            // this.addRoleArr.type = row.type
            this.readctRoleShow = true
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },
    readctSubmit() {
      //编辑提交
      let function_id = [] //最终的提交id
      let grandfather_id = [] //记录订单id
      let father_id = [] //记录父级id
      let checkedCities = [...this.addRoleArr.checkedCities] //当选择的id
      let roleFunctionArr = [...this.roleFunctionArr] //角色权限数组
      for (let i = 0;i < checkedCities.length;i++) {
        for (let n = 0;n < roleFunctionArr.length;n++) {
          for (let k = 0;k < roleFunctionArr[n].child.length;k++) {
            for (let j = 0;j < roleFunctionArr[n].child[k].child.length;j++) {
              if (checkedCities[i] == roleFunctionArr[n].child[k].child[j].id) {
                let grandfatherNum = grandfather_id.indexOf(roleFunctionArr[n].id)
                if (grandfatherNum == -1) {
                  grandfather_id.push(roleFunctionArr[n].id)
                }
                let fatherNum = father_id.indexOf(roleFunctionArr[n].child[k].id)
                if (fatherNum == -1) {
                  father_id.push(roleFunctionArr[n].child[k].id)
                }
              }
            }
          }
        }
      }
      function_id = grandfather_id.concat(father_id, checkedCities)
      let permissions = function_id.join(',')
      if (this.addRoleArr.desc == null) {
        this.addRoleArr.desc = ''
      }
      let fn = new FormData()
      fn.append('id', this.addRoleArr.id) //角色名称
      fn.append('name', this.addRoleArr.name) //角色名称
      fn.append('permissions', permissions) //权限id
      fn.append('desc', this.addRoleArr.desc) //备注
      fn.append('channel', this.channel) //区分渠道
      // fn.append('type', this.addRoleArr.type) //角色类型
      this.$http.post(this.url + '/role/editRole', fn).then(
        res => {
          if (res.data.msg == '查询成功' || res.data.code == '200') {
            this.$message.success('编辑成功！')
            this.readctRoleShow = false
            this.close()
            this.getListRole() //获取角色列表
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },
    lookMember() {
      // 查看成员
      alert('查看成员')
    },
    deleteRole(row) {
      //删除角色
      this.$confirm('操作将删除当前角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let fn = new FormData()
          fn.append('id', row.id)
          fn.append('channel', this.channel) //区分渠道
          this.$http.post(this.url + '/role/deleteRole', fn).then(
            res => {
              if (res.data.code == '200') {
                this.getListRole() //获取角色列表
                this.close()
              } else if (res.data.code == '8886') {
                //code   8886  登录过期
                sessionStorage.clear()
                this.$alert('登录已过期，请重新登录 !', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    window.location = 'login.html'
                  }
                })
                return
              } else {
                this.$message.error(res.data.msg)
                return
              }
            },
            res => {
              this.$message.error('网络错误！')
              return
            }
          )
        })
        .catch(() => { })
    },
    toAdminList(row) {
      if (this.channel == 1) {
        const { href } = this.$router.resolve({
          path: '/adminList',
          query: {
            role_id: row.id
          }
        })
        window.open(href, '_blank')
      } else if (this.channel == 2) {
        this.$router.push({
          path: '/shopUserList',
          query: {
            role_id: row.id
          }
        })
      }
    }
  },
  filters: {}
}
</script>

<style scoped>
.dialog-footer {
  padding-left: 125px;
  text-align: left;
}
.roleFunctionBox {
  border: 1px solid #e8e8e8;
  border-radius: 5px;
  padding: 5px;
}
.roleFunctionBox .roleTitle {
  border-bottom: 1px solid #e8e8e8;
}
.roleFunctionBox .roleTitle h3 {
  padding-left: 5px;
  line-height: 30px;
}
.roleFunctionBox .roleTitle h3 span:nth-child(1) {
  display: inline-block;
  width: 110px;
}
.roleFunctionBox .menuName {
  width: 100px;
  padding: 10px 10px 0 0;
  font-size: 14px;
  color: #999999;
  text-align: right;
}
.roleFunctionBox .menFunction {
  width: 600px;
}
.row-info {
  padding: 5px 0;
}
@media (max-width: 767.78px) {
}

/* 上传 */
</style>



// WEBPACK FOOTER //
// src/components/AdminRoleList.vue